import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView,
    redirect:'/main',
    children:[
      { path: '/main', component: () => import('../views/WorkSpace.vue'), meta: { requiresAuth: true } },
      { path: '/signing', component: () => import('../views/sign/SigningView.vue'), meta: { requiresAuth: true } },
      { path: '/signingDetail', component: () => import('../views/sign/SigningDetailView.vue'), meta: { requiresAuth: true } },
      { path: '/editSigning', component: () => import('../views/sign/EditSigningView.vue'), meta: { requiresAuth: true } },
      { path: '/signingRecord', component: () => import('../views/sign/SigningRecordView.vue'), meta: { requiresAuth: true } },
      { path: '/service', component: () => import('../views/service/PendingServiceView.vue'), meta: { requiresAuth: true } },
      { path: '/serviceRecord', component: () => import('../views/service/ServiceRecordView.vue'), meta: { requiresAuth: true } },
      { path: '/resident', component: () => import('../views/resident/ResidentView.vue'), meta: { requiresAuth: true } },
      { path: '/residentDetail', component: () => import('../views/resident/ResidentDetailView.vue'), meta: { requiresAuth: true } },
      { path: '/editResident', component: () => import('../views/resident/EditResidentView.vue'), meta: { requiresAuth: true } },
      { path: '/message', component: () => import('../views/message/MessageView.vue'), meta: { requiresAuth: true } },
      { path: '/institute', component: () => import('../views/data/InstituteView.vue'), meta: { requiresAuth: true } },
      { path: '/doctor', component: () => import('../views/data/DoctorView.vue'), meta: { requiresAuth: true } },
      { path: '/disease', component: () => import('../views/data/DiseaseView.vue'), meta: { requiresAuth: true } },
      { path: '/item', component: () => import('../views/data/ServiceItemView.vue'), meta: { requiresAuth: true } },
      { path: '/role', component: () => import('../views/setting/RoleManagementView.vue'), meta: { requiresAuth: true } },
    ]
  },
  {path: '/login', component: () => import('../views/LoginView')}
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

router.beforeEach((to, from, next) => {
  const user = getUser(); // 调用全局方法获取用户信息
  const auth = to.matched.some(record => record.meta.requiresAuth);
  if (auth && !user) {
    // 如果需要登录且用户未登录，则重定向到登录页面
    next({ name: 'login' });
  } else {
    // 否则，允许导航
    next();
  }
});

export default router
